package com.shwread.android.qysw.activity.psychological;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.util.SparseIntArray;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.NewActionHelp;
import com.ciko.code.base.BaseActicity;
import com.ciko.code.utils.NetWorkUtils;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.QyReaderApp;
import com.shwread.android.qysw.bean.psychological.OptionBean;
import com.shwread.android.qysw.bean.psychological.QueDetailedBean;
import com.shwread.android.qysw.bean.psychological.QueInfo;
import com.shwread.android.qysw10000229.R;
import com.shwread.android.ui.dialog.NetworkDialog;
import com.shwread.http.base.ObjectHttpResponseHandler;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import logic.util.Util;
import logic.util.Utils;

/**
 * 问卷详情
 */
public class EvaluatingQuestionnaireDetailActivity extends BaseActicity implements QuePopupWindow.PopItemListener {
    /**
     * 问卷名
     */
    private TextView tvQueName;
    /**
     * 副标题
     */
    private TextView tvQueSubItem;
    /**
     * 上一题
     */
    private Button btnPreviousQue;
    /**
     * 目录
     */
    private Button btnQueCatalog;
    /**
     * 下一题
     */
    private Button btnNextQue;
    private ViewPager vpQue;
    private int queId;
    /**
     * 得分
     */
    private int source;
    /**
     * 问卷答案列表
     */
    public static ArrayList<OptionBean> QueList = new ArrayList<>();
    public static SparseIntArray sourceList = new SparseIntArray();
    /**
     * 问卷题目列表
     */
    private List<QueInfo> list;
    /**
     * 当前位置
     */
    private int index;
    private QueDetailedBean.QuestInfoBean questInfoBean;

    @Override
    protected void initTopBar() {
        setTitle("心理评测");
        enableNavLeftImg();
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_questionnaire_detail);
    }

    @Override
    protected void initView() {
        vpQue = findViewByID(R.id.vp_que);
        tvQueName = findViewByID(R.id.tv_que_name);
        tvQueSubItem = findViewByID(R.id.tv_que_sub_item);
        btnPreviousQue = findViewByID(R.id.btn_previous_que);
        btnQueCatalog = findViewByID(R.id.btn_que_catalog);
        btnNextQue = findViewByID(R.id.btn_next_que);
    }

    @Override
    protected void initAdapter() {
    }

    @Override
    protected void initDates() {
        QueList.clear();
        sourceList.clear();
        if (!NetWorkUtils.isConnected(this)) {
            new NetworkDialog(this).show();
            return;
        }
        queId = getIntent().getIntExtra("queId", -1);
        NewActionHelp.toExprienceQuestionnaire(this, queId, 0, new ObjectHttpResponseHandler<QueDetailedBean>() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                Log.e("sss", "失败--" + s);
                Utils.showToast(QyReaderApp.application, "加载失败");
            }

            @Override
            public void onSuccess(int i, Header[] headers, QueDetailedBean queDetailedBean, String s) {
                Log.e("sss", "成功--" + s);
                questInfoBean = queDetailedBean.getQuestInfo();
                tvQueName.setText(questInfoBean.getTitle());
                tvQueSubItem.setVisibility(View.GONE);
                list = questInfoBean.getQuestionnaireItemInfos();
                for (QueInfo queInfo : list) {
                    QueList.add(new OptionBean()
                            .setItemId(queInfo.getId())
                            .setItemType("1"));//只存在单选情况
                }
                vpQue.setAdapter(fpAdapter);
                if (list.size() <= 1) {
                    btnNextQue.setBackgroundResource(R.drawable.img_que_submit);
                }
            }

            @Override
            public Type getType() {
                return new TypeToken<QueDetailedBean>() {
                }.getType();
            }
        });
    }

    @Override
    protected void initListener() {
        btnPreviousQue.setOnClickListener(this);
        btnQueCatalog.setOnClickListener(this);
        btnNextQue.setOnClickListener(this);
        //viewpager滑动监听
        vpQue.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {//滑动监听
                index = position;
                if (position + 1 == fpAdapter.getCount()) {
                    btnNextQue.setBackgroundResource(R.drawable.img_que_submit);
                } else {
                    btnNextQue.setVisibility(View.VISIBLE);
                    btnNextQue.setBackgroundResource(R.drawable.img_que_next);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.btn_previous_que://上一页
                if (vpQue.getCurrentItem() > 0) {
                    vpQue.setCurrentItem(vpQue.getCurrentItem() - 1, true);
                } else {
                    Utils.showToast(this, "已经是第一题了");
                }
                break;
            case R.id.btn_que_catalog://目录
                new QuePopupWindow(this).showPopupWindow(index, QueList, this);
                break;
            case R.id.btn_next_que:
                if (vpQue.getCurrentItem() < fpAdapter.getCount() - 1) {//下一题
                    vpQue.setCurrentItem(vpQue.getCurrentItem() + 1, true);
                } else {//提交
                    for (int i = 0; i < QueList.size(); i++) {
                        if (!QueList.get(i).isFinish()) {
                            Util.showToast(QyReaderApp.application, "请答完所有题再进行提交");
                            vpQue.setCurrentItem(i, false);
                            return;
                        }
                    }
                    btnNextQue.setEnabled(false);
                    source = 0;
                    for (int i = 0; i < sourceList.size(); i++) {
                        source += sourceList.valueAt(i);
                    }
                    NewActionHelp.toFinishExperienceQuestionnaire(this, queId, source, new ObjectHttpResponseHandler<HashMap<String, String>>() {
                        @Override
                        public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                            Log.e("sss", "失败--" + s);
                            Util.showToast(QyReaderApp.application, "提交失败");
                            btnNextQue.setEnabled(true);
                        }

                        @Override
                        public void onSuccess(int i, Header[] headers, HashMap<String, String> map, String s) {
                            Log.e("sss", "成功--" + s);
                            String result = map.get("result");
                            if (result != null) {
                                toConclusionActivity(result);
                            }
                            btnNextQue.setEnabled(true);
                        }

                        @Override
                        public Type getType() {
                            return new TypeToken<HashMap<String, String>>() {
                            }.getType();
                        }
                    });
                }
                break;
        }
    }

    /**
     * 跳转到评测结果页面
     */
    private void toConclusionActivity(String result) {
        Intent intent = new Intent(this, EvaluatingConclusionActivity.class);
        intent.putExtra("result", result);
        intent.putExtra("source", source);
        intent.putExtra("title", questInfoBean.getTitle());
        startActivity(intent);
        finish();
    }

    private FragmentPagerAdapter fpAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
        @Override
        public Fragment getItem(int position) {
            return EvaluatingQuestionItemFragment.newInstance(position, list.get(position));
        }

        @Override
        public int getCount() {
            return list == null ? 0 : list.size();
        }
    };

    @Override
    public void click(int position) {
        vpQue.setCurrentItem(position, false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        NewActionHelp.cancel(this);
    }
}